package fun.stgoder.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(3);

        new Thread(() -> {
            countDownLatch.countDown();
            System.out.println("--");
        }).start();

        new Thread(() -> {
            countDownLatch.countDown();
            System.out.println("--");
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
            System.out.println("--");
        }).start();

        countDownLatch.await();

        System.out.println("finish");

        System.out.println("-----------------------------");

        f1();
    }

    public static void f1() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        CountDownLatch countDownLatch1 = new CountDownLatch(1);

        List<Integer> list = new ArrayList<>();

        new Thread(() -> {
            while (list.size() != 5) {
                System.out.println("t0 size != 5, == " + list.size() + ", wait");
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t0 size == " + list.size() + ", exit");
                countDownLatch1.countDown();
                break;
            }
        }).start();

        TestUtil.sleepSeconds(1);

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                list.add(i);
                System.out.println("t1 add " + i);
                if (list.size() == 5) {
                    countDownLatch.countDown();
                    try {
                        countDownLatch1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //TestUtil.sleepSeconds(1);
            }
        }).start();


    }
}




